package net.kleinhenz.norabase.server;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Hashtable;

public class BeanHelper {

	private static Hashtable<Class<?>, Hashtable<String, PropertyDescriptor>> classDescs = new Hashtable<Class<?>, Hashtable<String, PropertyDescriptor>>();

	private static Hashtable<String, PropertyDescriptor> getPropDescs(Class<?> beanClass) throws IntrospectionException {

		if (classDescs.contains(beanClass))
			return classDescs.get(beanClass);
		
		Hashtable<String, PropertyDescriptor> table = new Hashtable<String, PropertyDescriptor>();

		BeanInfo info = Introspector.getBeanInfo(beanClass);
		PropertyDescriptor[] propDesc = info.getPropertyDescriptors();

		for (int i = 0; i < propDesc.length; i++)
			table.put(propDesc[i].getName(), propDesc[i]);
		
		classDescs.put(beanClass, table);
		return table;
	}

    public static Object getPropertyValue(Object bean, String name) throws Exception {

		PropertyDescriptor propDesc = (PropertyDescriptor) getPropDescs(bean.getClass()).get(name);
		if (propDesc == null) {
			throw new NoSuchFieldException("Error: property not found: " + name);
		}
		Method getter = propDesc.getReadMethod();
		if (getter == null) {
			throw new NoSuchMethodException("No read method for: " + name);
		}
		return getter.invoke(bean, new Object[] {});
    }
}
